<?php


namespace app\tickets\controller;

use JsApiPay;
use think\Db;
use think\Exception;
use WxPayApi;
use WxPayConfig;
use WxPayJsApiPay;
use WxPayRefund;
use WxPayUnifiedOrder;

require_once ROOT_PATH."extend/wxpay/lib/WxPay.Api.php";
require_once ROOT_PATH."extend/wxpay/example/WxPay.JsApiPay.php";
class Jsapi
{
//退款操作
    public function refund($out_trade_no,$total_fee,$refund_fee){
        $input = new WxPayRefund();
        $input->SetOut_trade_no($out_trade_no);
        $input->SetTotal_fee($total_fee);
        $input->SetRefund_fee($refund_fee);
        $input->SetOut_refund_no(WxPayConfig::MCHID.date("YmdHis"));
        $input->SetOp_user_id(WxPayConfig::MCHID);
        $black = WxPayApi::refund($input);
        return $black;
    }


    /**
     * 微信支付
     * @param $cartAmount
     * @param $openId
     * @param $orderId
     * @param $orderSn
     * @return mixed
     * @throws \WxPayException
     * @author zhixuedong
     * @date 2021/1/28/028
     */
    public function appletPay($cartAmount, $openId, $orderId, $orderSn,$body,$appid)
    {
        $tools = new JsApiPay();
        //订单号
        $money = $cartAmount * 100;
        $openid = $openId;
        $input = new \WxPayUnifiedOrder();

        $input = new WxPayUnifiedOrder();
        $input->SetBody($body);
        $input->SetAttach($body);
        $input->SetOut_trade_no($orderSn);
        $input->SetTotal_fee($money);
        $input->SetTime_start(date("YmdHis"));
        $input->SetTime_expire(date("YmdHis", time() + 600));
        $input->SetGoods_tag($body);
        $input->SetNotify_url("http://".$_SERVER['SERVER_NAME']."/tickets/Notify/notify");
        $input->SetTrade_type("JSAPI");
        $input->SetOpenid($openid);
        $order = WxPayApi::unifiedOrder($input);
        $jsApiParameters = $tools->GetJsApiParameters($order);

        $jsApiParameters = json_decode($jsApiParameters,true);
        $data['timeStamp'] = $jsApiParameters['timeStamp'];
        $data['nonceStr'] = $jsApiParameters['nonceStr'];
        $data['signType'] = $jsApiParameters['signType'];
        $data['package'] = $jsApiParameters['package'];
        $data['paySign'] = $jsApiParameters['paySign'];
        $data['out_trade_no'] = $orderSn;
        $data['orderid'] = $orderId;
        return $data;
    }


}